package com.dyzs.activity;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.dyzs.client.LoginClient;
import com.dyzs.util.Constants;
import com.dyzs.util.HttpDownloader;
import com.dyzs.util.ReadProperties;
import com.dyzs.util.ToolUtils;

public class LoginActivity extends CommonActivity {
	private Button loginBt, escBt;
	private EditText nameET, wordET;
	private String userName, userPassword;
	private CheckBox cbword, cbnot,cbzddl;

	private final String androidName = "dyzs.apk";
	public ProgressDialog myProDialog;	

	boolean flag=false;	
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		findView();
		initView();	
	}

	private void findView() {
		cbzddl=(CheckBox) findViewById(R.id.login_cb_zddl);	
		cbzddl.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView,	boolean isChecked) {
				if(isChecked){
					cbword.setChecked(true);
				}
			}
		});
		cbword = (CheckBox) findViewById(R.id.login_cb_visible);
		cbword.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView,	boolean isChecked) {
				if(!isChecked){
					cbzddl.setChecked(false);
				}
			}
		});
		cbnot = (CheckBox) findViewById(R.id.login_cb_nonet);
		nameET = (EditText) findViewById(R.id.login_account);
		wordET = (EditText) findViewById(R.id.login_password);
		loginBt = (Button) findViewById(R.id.login_btn_login);
		loginBt.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				login();
			}
		});
		escBt = (Button) findViewById(R.id.login_btn_esc);
		escBt.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				nameET.setText("");
				wordET.setText("");
				cbword.setChecked(false);
				nameET.requestFocus();
			}
		});
	}
	
	
	public void login(){
		flag=false;		
		if (cbnot.isChecked()) {
			Constants.LOGIN_NONET = true;
		} else {
			Constants.LOGIN_NONET = false;
		}
		userName = nameET.getText().toString().trim();
		userPassword = wordET.getText().toString().trim();
		if (userName.equals("") && userPassword.equals("")) {
			Toast.makeText(LoginActivity.this, "账号和密码不能为空",Toast.LENGTH_SHORT).show();			
			nameET.requestFocus();
		} else if (userName.equals("")) {
			Toast.makeText(LoginActivity.this, "账号不能为空",Toast.LENGTH_SHORT).show();	
			nameET.requestFocus();
		} else if (userPassword.equals("")) {
			Toast.makeText(LoginActivity.this, "密码不能为空",Toast.LENGTH_SHORT).show();	
			wordET.requestFocus();
		} else {
			if (Constants.LOGIN_NONET) {
				if (getInitParams().get(Constants.SHARE_LOGIN_USERNAME) != null) {
					String name = String.valueOf(getInitParams().get(Constants.SHARE_LOGIN_USERNAME));
					String word = String.valueOf(getInitParams().get(Constants.SHARE_LOGIN_PASSWORD));
					if (!name.equals(userName)) {							
						Toast.makeText(LoginActivity.this, "请先在线登录一次",Toast.LENGTH_SHORT).show();	
					} else if (!word.equals(userPassword)) {							
						Toast.makeText(LoginActivity.this, "密码错误，请重新输入",Toast.LENGTH_SHORT).show();	
					} else {
						Map userMap = new HashMap();
						userMap.put(Constants.SHARE_LOGIN_USERNAME,userName);
						userMap.put(Constants.SHARE_LOGIN_PASSWORD,userPassword);
						userMap.put(Constants.SHARE_LOGIN_REMBER_CHECKBOX, cbword.isChecked());
						userMap.put(Constants.SHARE_LOGIN_ZDDL_CHECKBOX, cbzddl.isChecked());
						savaInitParams(userMap);
						changeView(name);
					}
				} else {						
					Toast.makeText(LoginActivity.this, "请先在线登录一次",Toast.LENGTH_SHORT).show();	
				}
			} else {								
					showLoginProgressDialog("登录中...", "登录中,请稍后......");
						new Thread(new Runnable() {
							public void run() {
								try {
									LoginClient loginClient=new LoginClient();	
									String result = loginClient.getData(userName, userPassword);
									final Map map=	loginClient.pullXml(result);					
									LoginActivity.this.runOnUiThread(new Runnable() {
										public void run() {
											myProDialog.dismiss();											
											final String serverUrl= map.get("gx").toString();
											if(!("").equals(serverUrl)){																			              
												new AlertDialog.Builder(LoginActivity.this).setTitle("升级选项").setIcon(R.drawable.attachment).setMessage(
														"发现新版本，需要升级！").setPositiveButton("确定",
												        new DialogInterface.OnClickListener() {
												            public void onClick(DialogInterface dialog, int whichButton) {  					            	
												            	update(serverUrl);
												            }
												        }).show();	
											}else{
												if(map.get("result").toString().equals("1"))
													loginData(map);
												else if(map.get("result").toString().equals("2"))
													onException(new  Exception (map.get("value").toString()));
													
											}																					
										}
									});
								} catch (Exception e) {
									onException(e);
								}
							}
						}).start();				
				
			}
		}
	
	}

	private void changeView(String userName) {
		
		Constants.USER_Mobile = userName;
		Intent it = new Intent(LoginActivity.this, MainActivity.class);
		it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		if(flag)
			return;
		startActivity(it);
		this.finish();
	}

	private void initView() {
		if (getInitParams().get(Constants.SHARE_LOGIN_USERNAME) != null) {
			nameET.setText(String.valueOf(getInitParams().get(Constants.SHARE_LOGIN_USERNAME)));

			Boolean zddl = Boolean.valueOf(String.valueOf(getInitParams().get(Constants.SHARE_LOGIN_ZDDL_CHECKBOX)));
			if(zddl){					
				cbzddl.setChecked(true);
				cbword.setChecked(true);
				wordET.setText(String.valueOf(getInitParams().get(Constants.SHARE_LOGIN_PASSWORD)));
				login();
			}else{
				Boolean b = Boolean.valueOf(String.valueOf(getInitParams().get(Constants.SHARE_LOGIN_REMBER_CHECKBOX)));
				if (b == true) {
					wordET.setText(String.valueOf(getInitParams().get(Constants.SHARE_LOGIN_PASSWORD)));
					cbword.setChecked(true);
				}
			}			
		}
	}

	
	private void update(final String serverUrl) {		
		showProgressDialog("升级中...", "升级中,请稍后......", true, true);
		new Thread(new Runnable() {
			public void run() {
				try {
					HttpDownloader hd = new HttpDownloader();
					final int intParameter = hd.downFileInSd(serverUrl, ReadProperties.getPropertyByStr("client.filepaht"), androidName);
					LoginActivity.this.runOnUiThread(new Runnable() {
						public void run() {
							proDialog.dismiss();	
							try{								
								if (intParameter == 0) {												
									String filePath = Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator + ReadProperties.getPropertyByStr("client.filepaht") + File.separator + androidName;
									Intent i = new Intent(android.content.Intent.ACTION_VIEW);
									i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
									i.setDataAndType(Uri.fromFile(new File(filePath)),"application/vnd.android.package-archive");
									startActivity(i);						
								} else if (intParameter== 1) {
									throw new Exception(getResources().getString(R.string.no_sd));								
								} else if (intParameter == -1) {
									throw new Exception("更新失败");									
								}								
								
							}catch(Exception e){
								onException(e);
							};
						}
					});
				} catch (Exception e) {
					onException(e);
				}
			}
		}).start();
	}
	

	private void  loginData(Map map){
		if(flag)
			return;
		Map userMap = new HashMap();
		userMap.put(Constants.SHARE_LOGIN_USERNAME, userName);
		userMap.put(Constants.SHARE_LOGIN_PASSWORD,	userPassword);
		userMap.put(Constants.SHARE_LOGIN_REMBER_CHECKBOX, cbword.isChecked());
		userMap.put(Constants.SHARE_LOGIN_ZDDL_CHECKBOX, cbzddl.isChecked());
		savaInitParams(userMap);
		Constants.USER_ID = map.get("value").toString();
		changeView(userName);		
		
	}
	
	
	
	
	
	
	protected void showLoginProgressDialog(String title,String content) {		
		myProDialog = new ProgressDialog(LoginActivity.this);		
//		myProDialog.setTitle(title);
		//设置提示信息
		myProDialog.setMessage(content);
		//设置标题图片
//		myProDialog.setIcon(R.drawable.icon);
		//设置进度条是否不明确
		myProDialog.setIndeterminate(false);
		//设置是否可按返回键取消
		myProDialog.setCancelable(true);		
		myProDialog.setButton("取消", new DialogInterface.OnClickListener(){	
			public void onClick(DialogInterface dialog, int which) {
				myProDialog.cancel();	
				flag=true;
			}
			});		
		
		myProDialog.show();
	}
	private void onException(final Exception e) {
		LoginActivity.this.runOnUiThread(new Runnable() {
			public void run() {
				if (myProDialog != null) {
					myProDialog.dismiss();
				}
				if (proDialog != null) {
					proDialog.dismiss();
				}
				ToolUtils.toastText(LoginActivity.this,e.getMessage());							
			}
		});
	}
	
	
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			back();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}


	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, 0, 0, "退出");
		menu.add(0, 1, 1, "关于");
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case 0:
			back();
			break;
		case 1:
			View ve=LayoutInflater.from(LoginActivity.this).inflate(R.layout.about, null);
			TextView tv=(TextView)ve.findViewById(R.id.about_version);
			tv.setText(tv.getText()+ReadProperties.getPropertyByStr("client.version"));
			 new AlertDialog.Builder(this)
             .setTitle("关于")
             .setView(ve)
             .setPositiveButton("确定", new DialogInterface.OnClickListener(){
                 public void onClick(DialogInterface dialog, int button){}
             })
             .show();
			break;
		}
		return true;
	}

	private void back() {
		android.os.Process.killProcess(android.os.Process.myPid());
		finish();
	}

	

}